package authority

import (
	"context"
	"fmt"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/backendclient"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetApiAuthorityLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetApiAuthorityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApiAuthorityLogic {
	return &GetApiAuthorityLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetApiAuthorityLogic) GetApiAuthority(req *types.IDReq) (resp *types.ApiAuthorityListResp, err error) {
	if req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	role, err := l.svcCtx.BackendRpc.GetRoleById(l.ctx, &backendclient.IDReq{
		Id: req.Id,
	})
	if err != nil {
		return
	}

	if role.Code == nil || len(*role.Code) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	data := l.svcCtx.Casbin.GetFilteredPolicy(0, *role.Code)
	logrus.Info(fmt.Sprintf("GetApiAuthority id: %d, data: %+v", req.Id, data))
	resp = &types.ApiAuthorityListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.ApiAuthorityListInfo{
			BaseListInfo: types.BaseListInfo{
				Total: uint64(len(data)),
			},
		},
	}
	for _, v := range data {
		resp.Data.List = append(resp.Data.List, &types.ApiAuthorityInfo{
			Path:   pointy.GetPointer(v[1]),
			Method: pointy.GetPointer(v[2]),
		})
	}

	return resp, nil
}
